<template>
  <div style="padding: 10px; display: flex; flex-direction: column; height: 100%;">
    <!-- 添加或修改监控预案对话框 -->
    <el-form ref="cameraMonitorPlanFormRef" :model="form" :rules="rules" label-width="80px" style="height: calc(100% - 50px); display: flex; flex-direction: column;">
      <el-form-item label="预案名称" prop="monitorPlanName">
        <el-input v-model="form.monitorPlanName" maxlength="20" placeholder="请输入监控预案名称" />
      </el-form-item>
      <el-form-item label="是否轮播" prop="whetherCarousel">
        <el-radio-group v-model="form.whetherCarousel" @change="lunfanTimeChange">
          <el-radio :value="1" >是</el-radio>
          <el-radio :value="2" >否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.whetherCarousel == 1" label="轮播时间" prop="carouselTime" >
        <el-input-number v-model="form.carouselTime" :mix="1" :max="999" :disabled="!lunfanTime" :controls-position="controlsPosition" placeholder="请输入轮播时间" />&nbsp;秒
      </el-form-item>
      <el-form-item label="选择视频" prop="equipmentIds" class="select-camera-form-item">
        <div style="height: 100%; width: 48%; display: flex; flex-direction: column;">
          <div style="margin-bottom: 20px; font-size: 18px;">所有设备</div>
          <el-table ref="multipleTableRef" v-loading="cameraLoading" :data="equipmentList" border style="flex: 1;" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="设备名称" align="center" prop="equipmentName" width="150px" show-overflow-tooltip />
          <el-table-column label="设备识别码" align="center" prop="deviceId" show-overflow-tooltip />
        </el-table>
        <div style="width: 100%; display: flex; justify-content: flex-end; align-items: center;">
          <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total"  size="small"  layout="total, prev, pager, next" @pagination="getEquipmentList"/>
        </div>
        </div>

        <div style="height: 100%; width: 48%; display: flex; flex-direction: column;">
          <div style="margin-bottom: 20px; font-size: 18px;">已选设备</div>
          <el-table :data="selectedEquipmentList" border style="flex: 1; margin-bottom: 35px;">
          <el-table-column label="设备名称" align="center" prop="equipmentName" width="150px" show-overflow-tooltip />
          <el-table-column label="设备识别码" align="center" prop="deviceId" show-overflow-tooltip />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px" fixed="right">
            <template #default="scope">
                <el-button link type="primary" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        </div>
      </el-form-item>
    </el-form>
    <div style="height: 50px; display: flex; justify-content: center; align-items: center;">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="emit('close')">取 消</el-button>
    </div>
  </div>
</template>

<script setup name="cameraMonitorPlan" lang="ts">
import { addcameraMonitorPlan } from '@/api/security/video-monitor/camera-monitor-plan';
import { cameraMonitorPlanForm } from '@/api/security/video-monitor/camera-monitor-plan/types';
import { cameraInfoVO } from '@/api/security/camera/camera-info/types';
import request from '@/utils/request';
import { c } from 'vite/dist/node/types.d-aGj9QkWt';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const buttonLoading = ref(false);
const lunfanTime = ref(false);
const total = ref(0);
const cameraMonitorPlanFormRef = ref<ElFormInstance>();
const selectedEquipmentList = ref([]);
const lockTableSelectionChange = ref(false);
const multipleTableRef = ref<any>();
const cameraLoading = ref(false);
const equipmentList = ref<cameraInfoVO[]>([]);
const initFormData: cameraMonitorPlanForm = {
  cameraMonitorPlanId: undefined,
  remark: undefined,
  monitorPlanName: undefined,
  whetherCarousel:undefined,
  carouselTime: undefined,
  equipmentIds: undefined
}
const data = reactive({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    monitorPlanName: undefined,
    carouselTime: undefined,
    startTime:undefined,
    endTime:undefined,
    startTimeDesc:undefined,
    endTimeDesc:undefined,
    params: {}
  },
  rules: {
    cameraMonitorPlanId: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    monitorPlanName: [{ required: true, message: '监控预案名称不能为空', trigger: 'blur' }],
    equipmentIds: [{ required: true, message: '监控不能为空', trigger: 'blur' }],
    whetherCarousel: [{ required: true, message: '是否轮播不能为空', trigger: 'blur' }],
    carouselTime: [{ required: true, message: '轮播时间不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const emit = defineEmits(['close', 'success']);


/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  equipmentNames.value = ''
  cameraMonitorPlanFormRef.value?.resetFields();
};

/** 获取设备列表 */
const getEquipmentList = async () => {
  cameraLoading.value = true;
  lockTableSelectionChange.value = true;  // 锁定多选框选中数据
  const res = await request({ url: '/equipment/equipment-info/list', method: 'get', params: { dataSource: 2, ...queryParams.value }  }).finally(() => (cameraLoading.value = false))
  console.log('获取设备列表', res);

  equipmentList.value = res.rows;
  total.value = res.total;

  await nextTick(() => {
    equipmentList.value.forEach(equipment => {
      selectedEquipmentList.value.forEach(selectedEquipment => {
        if (selectedEquipment.equipmentId == equipment.equipmentId) {
          multipleTableRef.value!.toggleRowSelection( equipment, undefined, false )
        }
      });
    })
    // 解锁多选框选中数据
    lockTableSelectionChange.value = false;
  });
};

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  if(lockTableSelectionChange.value == false) {
    selection.forEach(item => {
      // 如果勾选设备不在已选设备列表中，则添加到已选设备列表
      let hasSelectedEquipment = selectedEquipmentList.value.find((selectedItem) => { return  selectedItem.equipmentId == item.equipmentId; })
      if(hasSelectedEquipment == null) {
        selectedEquipmentList.value.push(item);
      }
    })

    // 获取当前页面没有选中的设备，并将其从已选设备列表中移除
    let currPageNotSelectedEquipmentList = equipmentList.value.filter(equipment => { return !selection.includes(equipment) })
    console.log('已经选中的设备列表：', selectedEquipmentList.value)
    console.log('当前页面没有选中的设备列表：', currPageNotSelectedEquipmentList)
    currPageNotSelectedEquipmentList.forEach(currPageNotSelectedEquipment => {
      let currPageNotSelectedEquipmentIndex = selectedEquipmentList.value.findIndex((selectedItem) => { return  selectedItem.equipmentId == currPageNotSelectedEquipment.equipmentId; })
      console.log('当前页面没有选中的设备索引：', currPageNotSelectedEquipmentIndex)
      if(currPageNotSelectedEquipmentIndex != -1) {
        selectedEquipmentList.value.splice(currPageNotSelectedEquipmentIndex, 1);
      }
    })
  }
};

/** 删除按钮操作 */
const handleDelete = async (row) => {
  await proxy?.$modal.confirm('是否确认删除设备信息编号为"' + row.equipmentId + '"的数据项？');

  selectedEquipmentList.value.splice(selectedEquipmentList.value.indexOf(row), 1);

  equipmentList.value.forEach(equipment => {
    if (equipment.equipmentId == row.equipmentId) {
      multipleTableRef.value!.toggleRowSelection( equipment, false, false )
    }
  });
};


/** 轮播时间是否禁用 */
const lunfanTimeChange = (value) => {
  console.log('value12',value)
  lunfanTime.value = value == 1 ? true : false
  console.log('lunfanTime',lunfanTime.value)
}

/** 提交按钮 */
const submitForm = () => {
  if (selectedEquipmentList.value.length === 0) {
    proxy?.$message.error('请选择设备');
    return;
  }
  form.value.equipmentIds = [];
  // form.value.equipmentIds = selectedEquipmentList.value.map(item => { return { equipmentId: item.equipmentId } });
  form.value.equipmentIds = selectedEquipmentList.value.map(item => { return item.equipmentId });

  cameraMonitorPlanFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await addcameraMonitorPlan(form.value).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('操作成功');
      emit('close');
      reset();
      emit('success');
    }
  });
};

let equipmentNames = ref('')

onMounted(() => {
  getEquipmentList();
});
</script>
<style lang="scss" scoped>
:deep(.select-camera-form-item) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: hidden;
  .el-form-item__content {
    height: calc(100% - 40px);
    display: flex;
    flex-direction: column;
  }
}
</style>
